//
//  ECUShareView.m
//  Edu_iOS
//
//  Created by apple on 2017/9/25.
//  Copyright © 2017年 yanyan. All rights reserved.
//  分享界面 以后要接入shareSDK之类的三方

#define Icon_Width          172.f/1080.f*kScreenWidth      //图标的宽、高
#define Icon_Margin         49.f/1080.f*kScreenWidth*2     //图标之间的margin
#define CancelBtn_Height    145.f/1920.f*kScreenHeight     //取消按钮高度


#import "ECUShareView.h"

#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>

#import "WXApi.h"
#import "WeiboSDK.h"
#import <TencentOpenAPI/QQApiInterface.h>
@interface UICVCell_Share()
@property(nonatomic,strong)UIImageView *imageView;
@property(nonatomic,strong)UILabel *label;
@end

@implementation UICVCell_Share
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
    }
    return self;
}
- (void)addSubviews
{
    [super addSubviews];
    _imageView = [[UIImageView alloc]initWithFrame:CGRectMake(10,0 , Icon_Width, Icon_Width)];
    [self.contentView addSubview:_imageView];
    
    _label = [[UILabel alloc]init];
    _label.frame = CGRectMake(0, CGRectGetMaxY(_imageView.frame) + 60.f/1920.f*kScreenHeight, Icon_Width+20, 45.f/1920.f*kScreenHeight);
    _label.textAlignment = NSTextAlignmentCenter;
    _label.font = [UIFont systemFontOfSize:15*kPercentage];
    _label.textColor = [UIColor colorWithHexString:@"#6D7689"];
    [self.contentView addSubview:_label];

}
- (void)setObject:(id)object
{
    [super setObject:object];
    _imageView.image = [UIImage imageNamed:[object valueForKey:@"brief"]];
    _label.text = [object valueForKey:@"name"];
}
@end

@interface ECUShareView()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic, strong) UIView  *contentView;
@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)NSMutableArray *dataSource;

@end

@implementation ECUShareView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self layoutAllSubviews];
    }
    return self;
}

- (void)layoutAllSubviews{
    
    /*创建灰色背景*/
    UIView *bgView = [[UIView alloc] initWithFrame:self.frame];
    bgView.alpha = 0.3;
    bgView.backgroundColor = [UIColor blackColor];
    [self addSubview:bgView];
    
    /*添加手势事件,移除View*/
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissContactView:)];
    [bgView addGestureRecognizer:tapGesture];
    
    /*创建显示View*/
    _contentView = [[UIView alloc] init];
    _contentView.frame = CGRectMake(0, 1320.f/1920*kScreenHeight, kScreenWidth, 600.f/1920.f*kScreenHeight);
    _contentView.backgroundColor=[UIColor colorWithHexString:@"#F8F8F8"];
    _contentView.layer.cornerRadius = 4;
    _contentView.layer.masksToBounds = YES;
    [self addSubview:_contentView];
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_contentView addSubview:cancelBtn];
    cancelBtn.backgroundColor = [UIColor whiteColor];
    [cancelBtn setTitle:@"取消" forState:0];
    [cancelBtn setTitleColor:[UIColor colorWithHexString:@"#6D7689"] forState:0];
    cancelBtn.titleLabel.font = [UIFont systemFontOfSize:54.f/1920.f*kScreenHeight];
    [cancelBtn addTarget:self action:@selector(dismissContactView) forControlEvents:UIControlEventTouchUpInside];
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(_contentView);
        make.bottom.mas_equalTo(_contentView.mas_bottom);
        make.height.mas_equalTo(CancelBtn_Height);
    }];
    
    UIView *lineView = [[UIView alloc]init];
    [_contentView addSubview:lineView];
    lineView.backgroundColor = [UIColor colorWithHexString:@"#DEDEDE"];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(_contentView);
        make.bottom.mas_equalTo(cancelBtn.mas_top);
        make.height.mas_equalTo(1);
    }];
    
    _dataSource = [[NSMutableArray alloc]init];
    if ([WXApi isWXAppInstalled]) {
        [_dataSource addObject:@{@"name":@"微信",@"brief":@"sharedIcon_weChat"}];
    }
    
    if ([QQApiInterface isQQInstalled]) {
        [_dataSource addObject:@{@"name":@"QQ",@"brief":@"sharedIcon_QQ"}];
        [_dataSource addObject:@{@"name":@"QQ空间",@"brief":@"sharedIcon_QQZone"}];
    }
    
//    if ([WeiboSDK isWeiboAppInstalled]) {
//        [arr_title addObject:@"新浪微博"];
//        [arr_icon  addObject:@"sharedIcon_weibo"];
//    }
    
    WeakSelf(weakSelf);
    if (_dataSource.count == 0) {
        UILabel *tipLab = [[UILabel alloc]init];
        [_contentView addSubview:tipLab];
        tipLab.text = @"暂无可用的分享平台";
        tipLab.textColor = [UIColor colorWithHexString:@"#999999"];
        tipLab.font = [UIFont systemFontOfSize:14*kPercentage];
        tipLab.textAlignment = NSTextAlignmentCenter;
        
        [tipLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(weakSelf.contentView.mas_centerX);
            make.centerY.equalTo(weakSelf.contentView.mas_centerY).mas_offset(-20);
            make.height.mas_equalTo(20);
            make.width.mas_equalTo(kScreenWidth);
        }];
        
        return;
    } else {
        UICollectionViewFlowLayout *viewLayout = [[UICollectionViewFlowLayout alloc] init];
        viewLayout.itemSize = CGSizeMake(Icon_Width + 20, Icon_Width + 45.f/1920.f*kScreenHeight);
        viewLayout.minimumLineSpacing = 10;
        viewLayout.minimumInteritemSpacing = 10;
        viewLayout.sectionInset = UIEdgeInsetsMake(5, 20, 5, 20);
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 20, kScreenWidth, _contentView.height - CancelBtn_Height - 20) collectionViewLayout:viewLayout];
        _collectionView.clipsToBounds = NO;
        _collectionView.backgroundColor = [UIColor clearColor];//[UIColor colorWithRed:0.9686 green:0.9569 blue:0.8784 alpha:1];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [_collectionView registerClass:[UICVCell_Share class] forCellWithReuseIdentifier:@"cell"];
        [_contentView addSubview:_collectionView];
    }
    
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _dataSource.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICVCell_Share *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.object = [_dataSource objectAtIndex:indexPath.row];
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    SSDKPlatformType shareApiType;
    switch (indexPath.row) {
        case 0:
        {
            // 微信
//            shareApiType = SSDKPlatformSubTypeWechatTimeline;// 朋友圈
            shareApiType = SSDKPlatformSubTypeWechatSession;

        }
            break;
        case 1:
        {
            // QQ
            shareApiType = SSDKPlatformSubTypeQQFriend;

        }
            break;
        case 2:
        {
            // QQ 空间
            shareApiType = SSDKPlatformSubTypeQZone;

        }
            break;

        default:
            {
                shareApiType = SSDKPlatformSubTypeWechatTimeline;

            }
            break;
    }
    [shareParams SSDKSetupShareParamsByText:@"学缘课程分享"
                                     images:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.icon_course]]]
                                        url:[NSURL URLWithString:@"http://www.sdkhcm.com/"]
                                      title:self.title_course
                                       type:SSDKContentTypeWebPage];
    
    //进行分享
    [ShareSDK share:shareApiType //传入分享的平台类型
         parameters:shareParams
     onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) { // 回调处理....
         if (state == SSDKResponseStateSuccess) {
             [MBProgressHUD showTipMessageInWindow:@"分享成功"];
             [self dismissContactView];
         }else if (state == SSDKResponseStateFail){
             if (shareApiType == SSDKPlatformTypeSinaWeibo) {
                 [MBProgressHUD showTipMessageInWindow:@"分享成功"];
                 return;
             }
             [MBProgressHUD showTipMessageInWindow:@"分享失败"];
         }else if (state == SSDKResponseStateCancel){
             [MBProgressHUD showTipMessageInWindow:@"取消分享"];
             [self dismissContactView];
         }
         DLog(@"%ld",state);
         
     }];
}


#pragma mark - 手势点击事件,移除View
- (void)dismissContactView:(UITapGestureRecognizer *)tapGesture{
    
    [self dismissContactView];
}

-(void)dismissContactView{
    __weak typeof(self)weakSelf = self;
    [UIView animateWithDuration:0.5 animations:^{
        weakSelf.alpha = 0;
    } completion:^(BOOL finished) {
        [weakSelf removeFromSuperview];
    }];
    
}

// 这里加载在了window上
-(void)showView{
    UIWindow * window = [UIApplication sharedApplication].windows[0];
    [window addSubview:self];
}


@end
